import React, { useState, useRef, useEffect } from 'react';
import { Button, Input, Select, DatePicker, Space, Pagination, Form, message, Modal } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { DataType } from '../../pages/PDSData';
import DraggableTable from '@/components/DraggableTable';
import AddDataModal from './AddDataModal';
import request from '@/utils/request';
import dayjs from 'dayjs';

const { Option } = Select;
const { RangePicker } = DatePicker;

interface DataContentProps {
  datasetId: number;
  treeUuid: string;
}

interface ApiResponse {
  code: number;
  msg: string;
  data: {
    count: number;
    list: Array<{
      id: number;
      product_id: number;
      task_type: string;
      data_type: string;
      file_name: string;
      file_path: string;
      collection_time_start: string;
      collection_time_end: string;
      archive_time: string;
      data_size: number;
      station: string;
      dm_zhname: string;
      version_num: string;
      track_num_turns: number;
      data_level: string;
    }>;
    page: number;
    pages: number;
    page_size: number;
  };
}

interface FilterOptions {
  task_type: string[];
  dm_zhname: string[];
  data_level: string[];
}

const DataContent: React.FC<DataContentProps> = ({ datasetId, treeUuid }) => {
  const [tableData, setTableData] = useState<DataType[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [totalRecords, setTotalRecords] = useState(0);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [tableScrollY, setTableScrollY] = useState<number>(0);
  const tableContainerRef = useRef<HTMLDivElement>(null);
  const [addDataModalVisible, setAddDataModalVisible] = useState(false);
  const [columns, setColumns] = useState<ColumnsType<DataType>>([
    {
      title: '文件名',
      dataIndex: 'file_name',
      key: 'file_name',
      width: 300,
      ellipsis: { showTitle: false },
    },
    {
      title: '数据大小(MB)',
      dataIndex: 'size',
      key: 'size',
      width: 140,
      sorter: true,
      sortDirections: ['ascend', 'descend'] as const,
    },
    {
      title: '任务型号',
      dataIndex: 'task_type',
      key: 'task_type',
      width: 100,
      sorter: true,
      sortDirections: ['ascend', 'descend'] as const,
    },
    {
      title: '载荷',
      dataIndex: 'payload',
      key: 'payload',
      width: 100,
      sorter: true,
      sortDirections: ['ascend', 'descend'] as const,
    },
    {
      title: '数据级别',
      dataIndex: 'data_level',
      key: 'data_level',
      width: 100,
      sorter: true,
      sortDirections: ['ascend', 'descend'] as const,
    },
    {
      title: '采集开始时间',
      dataIndex: 'collect_start_time',
      key: 'collect_start_time',
      width: 180,
      sorter: true,
      sortDirections: ['ascend', 'descend'] as const,
    },
    {
      title: '采集结束时间',
      dataIndex: 'collect_end_time',
      key: 'collect_end_time',
      width: 180,
      sorter: true,
      sortDirections: ['ascend', 'descend'] as const,
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      fixed: 'right',
      align: 'center' as const,
      render: (_, record) => (
        <Button
          type="link"
          danger
          size="small"
          onClick={() => {
            Modal.confirm({
              title: '确认删除',
              content: '确定要删除这条数据吗？',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                try {
                  const response = await request<{ code: number; msg: string; data: any }>('/PDS/DataSetTemplateDataDelete', {
                    method: 'POST',
                    data: {
                      dataset_id: datasetId,
                      tree_uuid: treeUuid,
                      file_ids: [parseInt(record.key.toString())]
                    }
                  });

                  if (response.data.code === 200) {
                    message.success('删除成功');
                    fetchData({
                      page: currentPage,
                      pageSize,
                    });
                  } else {
                    message.error(response.data.msg || '删除失败');
                  }
                } catch (error) {
                  console.error('删除失败:', error);
                  message.error('删除失败');
                }
              }
            });
          }}
        >
          删除
        </Button>
      ),
    },
  ]);
  const [filterOptions, setFilterOptions] = useState<FilterOptions>({
    task_type: [],
    dm_zhname: [],
    data_level: []
  });

  // 获取数据列表
  const fetchData = async (params: any) => {
    try {
      setLoading(true);
      const response = await request<ApiResponse>('/PDS/DataSetTemplateList', {
        method: 'GET',
        params: {
          dataset_id: datasetId,
          tree_uuid: treeUuid,
          page: params.page,
          page_size: params.pageSize,
          task_type: params.task_type,
          dm_zhname: params.payload,
          data_level: params.data_level,
          collection_time__gte: params.collect_time_range?.[0]?.format('YYYY-MM-DD HH:mm:ss'),
          collection_time__lte: params.collect_time_range?.[1]?.format('YYYY-MM-DD HH:mm:ss'),
          file_name: params.keyword,
        },
      });

      if (response.data.code === 200) {
        const { list, count } = response.data.data;
        const formattedData = list.map(item => ({
          key: item.id.toString(),
          file_name: item.file_name,
          size: item.data_size,
          task_type: item.task_type,
          payload: item.dm_zhname,
          data_level: item.data_level,
          collect_start_time: item.collection_time_start,
          collect_end_time: item.collection_time_end,
          upload_time: item.archive_time,
          creator: '系统',
        }));
        setTableData(formattedData);
        setTotalRecords(count);
      } else {
        message.error(response.data.msg || '获取数据失败');
      }
    } catch (error) {
      console.error('获取数据失败:', error);
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取筛选选项
  const fetchFilterOptions = async () => {
    try {
      const response = await request<{ code: number; msg: string; data: FilterOptions }>('/PDS/DataSetTemplateFilter', {
        method: 'GET',
        params: {
          dataset_id: datasetId,
          tree_uuid: treeUuid
        }
      });

      if (response.data.code === 200) {
        setFilterOptions(response.data.data);
      } else {
        message.error(response.data.msg || '获取筛选选项失败');
      }
    } catch (error) {
      console.error('获取筛选选项失败:', error);
      message.error('获取筛选选项失败');
    }
  };

  // 计算表格滚动高度的函数
  const calculateTableScrollHeight = () => {
    if (tableContainerRef.current) {
      const containerHeight = tableContainerRef.current.clientHeight;
      const tableHeaderHeight = 24;
      const scrollHeight = containerHeight - tableHeaderHeight;
      setTableScrollY(scrollHeight);

      const body = tableContainerRef.current.querySelector('.ant-table-body');
      if (body) {
        (body as HTMLElement).style.height = Math.max(scrollHeight, 0) + 'px';
      }
    }
  };

  useEffect(() => {
    calculateTableScrollHeight();
    window.addEventListener('resize', calculateTableScrollHeight);

    return () => {
      window.removeEventListener('resize', calculateTableScrollHeight);
    };
  }, []);

  // 初始加载数据
  useEffect(() => {
    fetchData({
      page: currentPage,
      pageSize,
    });
    fetchFilterOptions();
  }, [datasetId, treeUuid]);

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    columnWidth: 50,
    onChange: onSelectChange,
  };

  const handlePageChange = (page: number, pageSize?: number) => {
    setCurrentPage(page);
    if (pageSize) {
      setPageSize(pageSize);
    }
    const values = form.getFieldsValue();
    fetchData({
      ...values,
      page,
      pageSize,
    });
  };

  const onFinish = (values: any) => {
    setCurrentPage(1);
    fetchData({
      ...values,
      page: 1,
      pageSize,
    });
  };

  // 处理添加数据
  const handleAddData = (selectedData: any[]) => {
    // 刷新数据列表
    fetchData({
      page: currentPage,
      pageSize,
    });
    setAddDataModalVisible(false);
  };

  // 处理删除数据
  const handleDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的数据');
      return;
    }

    Modal.confirm({
      title: '确认删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 条数据吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await request<{ code: number; msg: string; data: any }>('/PDS/DataSetTemplateDataDelete', {
            method: 'POST',
            data: {
              dataset_id: datasetId,
              tree_uuid: treeUuid,
              file_ids: selectedRowKeys.map(key => parseInt(key.toString()))
            }
          });

          if (response.data.code === 200) {
            message.success('删除成功');
            setSelectedRowKeys([]);
            // 刷新数据列表
            fetchData({
              page: currentPage,
              pageSize,
            });
          } else {
            message.error(response.data.msg || '删除失败');
          }
        } catch (error) {
          console.error('删除失败:', error);
          message.error('删除失败');
        }
      }
    });
  };

  return (
    <div className="data-management-right" style={{ flex: 1 }}>
      <Form form={form} layout="inline" className="filter-form" onFinish={onFinish} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
        <Form.Item name="collect_time_range" label="采集时间" style={{ width: 320 }}>
          <RangePicker style={{ width: '100%' }} placeholder={['开始时间', '结束时间']} />
        </Form.Item>

        <Form.Item name="keyword" label="关键字" style={{ width: 320 }}>
          <Input placeholder="输入数据集名称或关键字" style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item style={{ paddingLeft: 80, width: 320 }}>
          <Space>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
            <Button htmlType="button" onClick={() => {
              form.resetFields();
              fetchData({
                page: 1,
                pageSize,
              });
            }}>
              清除
            </Button>
          </Space>
        </Form.Item>
      </Form>

      <div style={{ marginBottom: 16 }}>
        <Space>
          <Button type="primary" onClick={() => setAddDataModalVisible(true)}>添加数据</Button>
          <Button danger onClick={handleDelete} disabled={selectedRowKeys.length === 0}>
            删除数据
          </Button>
        </Space>
      </div>

      <div ref={tableContainerRef} style={{ flex: 1, overflow: 'hidden' }}>
        <DraggableTable
          rowSelection={rowSelection}
          columns={columns}
          dataSource={tableData}
          pagination={false}
          bordered
          size="small"
          loading={loading}
          tableLayout="fixed"
          scroll={{
            y: tableScrollY,
            x: 'max-content'
          }}
          rowClassName={(_: any, index: number) => (index % 2 === 0 ? 'zebra-row-odd' : 'zebra-row-even')}
          onColumnsChange={(columns) => {
            setColumns(columns);
          }}
        />
      </div>

      <div style={{ marginTop: 16, display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
        <Pagination
          current={currentPage}
          pageSize={pageSize}
          total={totalRecords}
          onChange={handlePageChange}
          showSizeChanger
          showQuickJumper
          pageSizeOptions={['10', '20', '50']}
          showTotal={(total) => `共 ${total} 条`}
        />
      </div>

      <AddDataModal
        open={addDataModalVisible}
        onCancel={() => setAddDataModalVisible(false)}
        onOk={handleAddData}
        datasetId={datasetId}
        treeUuid={treeUuid}
      />
    </div>
  );
};

export default DataContent;